<template>
    <view class="container">
        <z-paging
            ref="paging"
            :scroll-with-animation="true"
        >
            <!-- 骨架屏区域开始 -->
            <uv-skeletons :loading="isSkeleton" :skeleton="skeletons"></uv-skeletons>
            <!-- 骨架屏区域结束 -->

            <template #top>
                <!-- 自定义导航区域开始 -->
                <TridentNavBar>
                    <template #left>
                        <!-- #ifdef MP-ALIPAY -->
                        <i class="iconfont icon-zuojiantou" style="font-size: 36rpx;font-weight: bold;"></i>
                        <!-- #else -->
                        <i class="iconfont icon-zuojiantou" style="font-size: 36rpx;"></i>
                        <!-- #endif -->
                    </template>
                    <template #default>群聊成员({{ groupChat.member.length }})</template>
                    <template #right >
                        <text style="border: 2rpx solid #fff;padding: 4rpx 15rpx;border-radius: 5rpx;" @click="handleDeleteMember">删 除</text>
                    </template>
                </TridentNavBar>
                <!-- 自定义导航区域结束 -->

                <!-- 搜索区域开始 -->
                <TridentSearch @search="handleSearchMember"/>
                <!-- 搜索区域结束 -->
            </template>

            <!-- 成员区域开始 -->
            <uv-index-list
                :index-list="Object.keys(memberList)"
                :activeColor="global.THEME_COLOR"
                customNavHeight="160rpx"
            >
                <template v-for="(item, index) in memberList">
                    <uv-index-item>
                        <uv-index-anchor
                            :text="index"
                            bgColor="#e2f8f3"
                            customNavHeight="50"
                        />
                        <view class="member-wrap">
                            <view
                                class="member-item"
                                v-for="(member, index) in item" :key="index"
                                @click="handleChange(member)"
                            >
                                <view class="check-box">
                                    <i class="iconfont icon-weixuanzhong" v-if="member.is_check == false"></i>
                                    <i class="iconfont icon-xuanzhong" v-else></i>
                                </view>
                                <view class="image-box">
                                    <image
                                        :src="member.avatar_url ? global.FILE_DOMAIN + member.avatar_url : '/static/images/default_avatar.png'"
                                    />
                                </view>
                                <text class="title-box">{{ member.username }}</text>
                            </view>
                        </view>
                    </uv-index-item>
                </template>
            </uv-index-list>
            <!-- 成员区域结束 -->
        </z-paging>
    </view>
</template>

<script lang="ts" setup>
import { reqGroupChatDetailAPI, reqRemoveMemberAPI } from '@/apis/groupChat'
import type { GroupChat, Member, RemoveMemberParams } from '@/types/groupChat'
import { pinyin } from 'pinyin-pro'
import { ref, inject, reactive } from 'vue'
import { onShow } from '@dcloudio/uni-app'

// --------------- 定义全局变量开始 ---------------
// 全局属性
const global: any = inject('global')

// 获取页面参数
const query = defineProps({
    "gid": {
        type: String,
        default: '0'
    }
})
// --------------- 定义全局变量结束 ---------------



onShow(async() => {
    for (let index = 0; index < 12; index++) {
        skeletons.push(skeleton as never)
    }

    await getGroupChatInfo()
})



// --------------- 处理删除成员开始 ---------------
const params = ref<RemoveMemberParams>({
    gid: query.gid as never,
    uids: '',
    network: 'ws'
})

// 处理复选框变化
const handleChange = (member: any) => {
    member.is_check = !member.is_check
    
    let uids = params.value.uids ? params.value.uids.split(',') : []

    if (member.is_check) {
        uids.push(member.uid)
    } else {
        const index = uids.findIndex(item => item == member.uid)
        uids.splice(index, 1)
    }

    params.value.uids = uids.join()
}

// 删除成员
const handleDeleteMember = () => {
    if (params.value.uids == '') {
        uni.showToast({
            title: '请选择要删除的成员',
            duration: 1000,
            icon: 'none'
        })
        
        return false
    }

    uni.showModal({
	    content: '确定要删除成员?',
        confirmColor: global.THEME_COLOR,
	    success: async (res) => {
	        if (res.confirm) {
                await reqRemoveMemberAPI(params.value)

                // 删除变量中的成员
                params.value.uids.split(',').forEach(uid => {
                    Object.keys(memberList.value).forEach(key => {
                        const index = memberList.value[key].findIndex((item: Member) => item.uid+'' == uid)
                        if (index != -1) {
                            if (memberList.value[key].length > 1) { // 如果只有一个成员则删除
                                memberList.value[key].splice(index, 1)
                            } else {
                                delete memberList.value[key]
                            }
                        }
                    })
                })

                uni.showToast({
                    title: '删除成员成功',
                    duration: 1000
                })
	        }
	    }
	})
}
// --------------- 处理删除成员结束 ---------------



// --------------- 处理搜索成员开始 ---------------
const username = ref<string>('')

// 搜索成员
const handleSearchMember = (e: any) => {
    username.value = e.keyword.value
    handleMemberList()
}
// --------------- 处理搜索成员结束 ---------------



// --------------- 处理群聊信息开始 ---------------
// 群聊信息
const groupChat = ref<GroupChat>({
    id: 0,
    name: '',
    member: [],
    note: '',
    update_time: '',
    create_time: ''
})

// 成员列表
const memberList: any = ref({})

// 获取群聊信息
const getGroupChatInfo = async () => {
    // 显示骨架屏
    isSkeleton.value = true

    const result = await reqGroupChatDetailAPI(query.gid as never)
    groupChat.value = result.data
    handleMemberList()

    // 隐藏骨架屏
    isSkeleton.value = false
}

// 数量成员列表数据
const handleMemberList = () => {
    let tempMemberList: any = {}
    groupChat.value.member.forEach(item => {
        item.is_check = false
        // item.info!.username = item.username || ''
        // item.info?.avatar_url = item.avatar_url
        if (username.value != '') {
            if (item.username == username.value) {
                let initial = pinyin(item.username, {pattern: 'first', toneType: 'none' }).substr(0, 1).toLocaleUpperCase()
    
                if (!tempMemberList[initial]) {
                    tempMemberList[initial] = []
                }

                tempMemberList[initial].push(item)
            }
        } else {
            let initial = pinyin(item.username, {pattern: 'first', toneType: 'none' }).substr(0, 1).toLocaleUpperCase()
    
            if (!tempMemberList[initial]) {
                tempMemberList[initial] = []
            }

            tempMemberList[initial].push(item)
        }
    });

    memberList.value = Object.keys(tempMemberList).sort().reduce((acc: any, key) => {
        acc[key] = tempMemberList[key];
        return acc;
    }, {});
}
// --------------- 处理群聊信息结束 ---------------



// --------------- 定义骨架变量开始 ---------------
// 定义是否显示骨架
const isSkeleton = ref(false)

// 定义骨架参数
const skeleton = reactive({
  type: 'flex',
  num: 1,
  style: 'padding: 15rpx 30rpx 15rpx 25rpx;background-color: #fff;border-bottom: 2rpx solid #f6f6f6;align-items: center;',
  children: [
    // 选择框区域
    {
      type: 'custom',
      num: 1,
      style: 'width: 42rpx;height: 42rpx;border-radius: 21rpx;margin-right: 20rpx;'
    },

    // 图片区域
    {
      type: 'custom',
      num: 1,
      style: 'width: 90rpx;height: 90rpx;border-radius: 10rpx;margin-right: 20rpx;'
    },

    {
      type: 'custom',
      num: 1,
      style: ['width: 180rpx;height: 40rpx;']
    }
  ]
})

const skeletons = reactive([])
// --------------- 定义骨架变量结束 ---------------
</script>

<style scoped lang="scss">
.container {
    // 成员区域开始
    .member-wrap {
        padding-left: 30rpx;
        background-color: #fff;
        // 成员明细区域开始
        .member-item {
            display: flex;
            align-items: center;
            .check-box {
                margin-right: 15rpx;
                .iconfont {
                    font-size: 40rpx;
                    color: #d4d4d4;
                }
                .icon-xuanzhong {
                    color: $uni-color-primary;
                }
            }
            .image-box {
                display: flex;
                align-items: center;
                justify-content: center;
                width: 90rpx;
                height: 90rpx;
                border-radius: 10rpx;
                border: 2rpx solid #d4d4d4;
                overflow: hidden;
                
                image {
                    width: 80rpx;
                    height: 80rpx;
                }
            }
            .title-box {
                flex: 1;
                margin-left: 30rpx;
                color: #000;
                font-size: 32rpx;
                border-bottom: 2rpx solid #EDEDED;
                padding: 50rpx 0;
            }
            &:last-child .title-box {
                border-bottom: none;
            }
        }
    }
}
</style>